package com.noah2021.controller;

import com.noah2021.error.BusinessException;
import com.noah2021.error.EmBusinessError;
import com.noah2021.response.CommonReturnType;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 〈〉
 *
 * @author Noah2021
 * @create 2021/2/5
 * @return
 */
public class BaseController {
    public static final String CONTENT_TYPE_FORMED = "application/x-www-form-urlencoded";

    //解决未被controller吸收的异常
    @ExceptionHandler(Exception.class)//当收到Exception类型的异常进入该方法
    @ResponseStatus(HttpStatus.OK)//即使收到异常也返回OK
    @ResponseBody
    public Object handlerException(HttpServletRequest request, Exception e) {
        Map<String, Object> data = new HashMap<>();
        if (e instanceof BusinessException) {
            BusinessException businessException = (BusinessException) e;
            data.put("errCode", businessException.getErrCode());
            data.put("errMsg", businessException.getErrMsg());
        } else {
            data.put("errCode", EmBusinessError.UNKNOWN_ERROR.getErrCode());
            data.put("errMsg", EmBusinessError.UNKNOWN_ERROR.getErrMsg());
        }
        return CommonReturnType.create(data, "fail");
    }
}